//
//  UserViewModel.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import Foundation
import Combine

@MainActor
class UserViewModel: ObservableObject {
    @Published var userInfo: UserInfo?
    @Published var userProfile: UserProfile?
    @Published var isLogin: Bool = false
    @Published var isLoading: Bool = false
    @Published var errorMessage: String?
    @Published var menuItems: [CenterMenuItem] = []
    
    private var cancellables = Set<AnyCancellable>()
    private let apiService = APIService.shared
    
    init() {
        // 检查本地登录状态
        checkLoginStatus()
        
        // 监听登录成功通知
        NotificationCenter.default.addObserver(forName: NSNotification.Name("UserDidLogin"), object: nil, queue: .main) { [weak self] _ in
            self?.checkLoginStatus()
        }
    }
    
    // MARK: - 检查登录状态
    func checkLoginStatus() {
        // 检查本地存储的token
        if let token = UserDefaults.standard.string(forKey: APIConfig.tokenName), !token.isEmpty {
            isLogin = true
            // 加载用户信息
            Task {
                await loadUserInfo()
            }
        } else {
            isLogin = false
            userInfo = nil
        }
    }
    
    // MARK: - 加载用户信息
    func loadUserInfo() async {
        guard isLogin else { return }
        
        isLoading = true
        errorMessage = nil
        
        do {
            // 调用API获取用户信息
            let response = try await apiService.fetchUserCenterInfo()
            
            // 从UserInfoData转换为UserInfo
            if let userInfoData = response.data {
                userInfo = UserInfo(
                    id: userInfoData.id,
                    nickname: userInfoData.nickname,
                    avatar: userInfoData.avatar,
                    phone: userInfoData.phone,
                    nowMoney: nil,
                    integral: userInfoData.integral,
                    experience: userInfoData.experience,
                    level: userInfoData.level,
                    levelName: userInfoData.isVip ? userInfoData.vipName : nil,
                    isPromoter: userInfoData.isVip,
                    payCount: nil,
                    spreadCount: nil,
                    isPaidMember: userInfoData.isPaidMember,
                    collectCount: userInfoData.collectCount,
                    couponCount: userInfoData.couponCount,
                    browseNum: userInfoData.browseNum,
                    spreadTime: nil,
                    userType: nil,
                    status: nil,
                    isDel: nil,
                    addTime: nil,
                    lastTime: nil,
                    cleanTime: nil,
                    addres: nil,
                    adminid: nil,
                    loginType: nil,
                    paidMemberPaidEntrance: userInfoData.paidMemberPaidEntrance
                )
            }
            

            isLoading = false
        } catch {
            errorMessage = "加载用户信息失败"
            print("Error loading user info: \(error)")
            isLoading = false
        }
    }
    
    // MARK: - 加载用户中心菜单
    // func loadMenuItems() async {
    //     do {
    //         let response = try await apiService.fetchUserCenterMenu()
    //         if let menuData = response.data {
    //             self.menuItems = menuData
    //         }
    //     } catch {
    //         print("Error loading menu items: \(error)")
    //     }
    // }
    
    // MARK: - 登出
    func logout() {
        // 清除本地存储的token
        UserDefaults.standard.removeObject(forKey: "userToken")
        
        // 重置状态
        isLogin = false
        userInfo = nil
        
        // 发送登出通知
        NotificationCenter.default.post(name: NSNotification.Name("UserDidLogout"), object: nil)
    }
}
